package com.jiyun.jiyunmall.jiyunmallthird.web;

import com.aliyun.oss.OSS;
import com.aliyun.oss.common.utils.IOUtils;
import com.aliyun.oss.model.OSSObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.WritableResource;
import org.springframework.util.StreamUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.charset.Charset;

/**
 * @author 86156
 * 文件名: OssController
 * 创建者: Z奇
 * 创建时间:2022-08-08 16:28
 * 描述: 这是一个示例
 */
@RestController
public class OssController {
    @Autowired
    private OSS ossClient;

    /**
     * 1指定一个本地文件 用于一会上传使用
     * 2拼接一个oss远程地址
     * 这两个注解目前用不到
     */
/*    @Value("classpath:/oss-test.json")
    private Resource localFile;

    @Value("oss://" + OssApplication.BUCKET_NAME + "/oss-test.json")
    private Resource remoteFile;*/

    private static final String BUCKET_NAME ="jiyunmall888";

    //上传图片
    @GetMapping("/upload")
    public String upload() {
        try {
            //从本地上传到阿里云
            ossClient.putObject(BUCKET_NAME, "ta.jpg", new FileInputStream("E:\\aa.jpg"));
        }
        catch (Exception e) {
            e.printStackTrace();
            return "upload fail: " + e.getMessage();
        }
        return "upload success";
    }

    //下载图片
    @GetMapping("/download")
    public String download() {
        try {
            //获取BUCKET_NAME中的ta.jpg文件
            OSSObject ossObject = ossClient.getObject(BUCKET_NAME,
                    "ta.jpg");
            //使用输入流获取对象中的内容
            InputStream objectContent = ossObject.getObjectContent();
            //保存到本地E盘下
            FileOutputStream fileOutputStream = new FileOutputStream("E:\\bb.jpg");
            byte[] bytes = new byte[1024];
            int len =0;
            while((len=objectContent.read(bytes))>0){
                fileOutputStream.write(bytes,0,len);
            }
            fileOutputStream.flush();
            fileOutputStream.close();
            objectContent.close();
            return "download success " ;
        }
        catch (Exception e) {
            e.printStackTrace();
            return "download fail: " + e.getMessage();
        }
    }

}
